package org.lonetree.tc.core.id;

/**
 * An IdentifiableItem is any object representing an item in the system that has
 * a unique identity, and whose identity is represented by a
 * ValidatedIdentifier. The equality of all IdentifiableItems is evaluated by
 * checking the equality of their ValidatedIdentifiers.
 */
public abstract class IdentifiableItem{
	
	protected abstract ValidatedIdentifier getIdentifier();
	
	protected abstract String getIdentifierType();
	
	protected void checkIdentifier(ValidatedIdentifier identifier){
		if(identifier == null)
			throw new NullPointerException("identifier (" + getIdentifierType() + ") cannot be null");
	}
	
	@Override
	public final boolean equals(Object o){
		if(o == null)
			return false;
		
		if(o == this)
			return true;
		
		if(getClass().equals(o.getClass())){
			IdentifiableItem i = (IdentifiableItem)o;
			return getIdentifier().equals(i.getIdentifier());
		}
		else{
			return false;
		}
	}
	
	@Override
	public final int hashCode(){
		return getIdentifier().hashCode();
	}
	
	@Override
	public String toString(){
		return getClass().getSimpleName() + "(" + identify() + ")";
	}
	
	private String identify(){
		ValidatedIdentifier id = getIdentifier();
		if(id != null)
			return id.getIdentifierString();
		else
			return "no identifier";
	}
}
